package org.rslai.autotest.core.page.impl;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.rslai.autotest.core.page.AbstractHelper;
import org.rslai.autotest.core.page.Frame;

/**
 * Frame处理<br>
 * 提供Frame切换等方法
 * @author rslai
 */
public class FrameImpl extends AbstractHelper implements Frame{
	private static String clazzAndMethod;

	public FrameImpl() {
		this.initCurrentFrame();
	}

	/**
	 * 是否在当前 Frame
	 * @param clazz 当前class，例: this.getClass()
	 * @return true是当前Frame，false不是当前frame
	 */
	private boolean isCurrentFrame(Class<?> clazz) {
		// 得到当前类名及方法名
		String tmpClazzAndMethod = "";
		for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
			if (clazz.getName().equals(ste.getClassName())) {
				tmpClazzAndMethod = ste.getClassName() + "." + ste.getMethodName();
				break;
			}
		}

		if (clazzAndMethod.equals(tmpClazzAndMethod)) {
			return true;
		} else {
			clazzAndMethod = tmpClazzAndMethod;
			return false;
		}
	}

	/**
	 * 切换一个Frame
	 * @param driver WebDriver
	 * @param by By
	 */
	private void switchToFrame(By by) {
		try {
			WebElement frame = this.driver().findElement(by);
			this.driver().switchTo().frame(frame);
		} catch (NoSuchElementException ex) {
			throw ex;
		}
	}

	@Override
	public void initCurrentFrame() {
		clazzAndMethod = ".";
	}

	@Override
	public void switchToFrame(Class<?> clazz, Object...frames) {
		if (!isCurrentFrame(clazz)) { // 是否在当前 Frame
			this.driver().switchTo().defaultContent(); // 却换到 defaultContent
			if (frames.length != 0) {
				for (Object frame : frames) {
					if (frame instanceof Integer) {
						this.driver().switchTo().frame((Integer)frame); // 按int切换frame
					}else if (frame instanceof String) { // 按String切换frame
						String frameXpathStr = "//iframe[@id='" + (String)frame + "'] | //iframe[@name='" + (String)frame + "'] | //frame[@id='" + (String)frame + "'] | //frame[@id='" + (String)frame + "']";
						this.switchToFrame(By.xpath(frameXpathStr)); 
					} else if (frame instanceof By) { // 按By切换frame
						this.switchToFrame((By)frame);
					} else {
						IllegalArgumentException e = new IllegalArgumentException("方法参数错误：发现未支持类型\r\n\t方法switchToFrame只支持如下四种类型：String、int、By");
						e.printStackTrace();
						throw e;
					}
				}
			}
		}
	}

}
